<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="exportExcel">excel导出</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table :data="list" border :default-sort="{ prop: 'workNumber', order: 'descending' }">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="员工头像" width="100">
            <template v-slot="{row}">
              <img
                v-imgerror="require('../../assets/微信截图_20221108094336.png')"
                :src="row.staffPhoto"
                alt=""
                style="width:100%"
                @click="showCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template v-slot="{row}">
              {{ formatData(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="correctionTime" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?userId=${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="AssignRole(row.id)">分配角色</el-button>
              <el-button v-allow="'delete'" type="text" size="small" @click="doDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-size="pagesize"
            layout="prev, next"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog v-if="showDialog" title="新增员工" :visible.sync="showDialog">
        <addor-edit @success="hSuccess" @close="showDialog = false" />
      </el-dialog>
      <el-dialog title="生成二维码图片" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <el-dialog title="分配角色" :visible.sync="AssignRoleDialog">
        <AssignRole :cur-id="curId" @success="AssignRoleDialog = false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import AssignRole from '@/views/employees/assignRole.vue'
import addorEdit from '@/views/employees/empDialog.vue'
import { delEmployees, getEmployees } from '@/api/employees'
import employeesEnum from '@/constant/employees'
import QRCode from 'qrcode'

// const hireType = {}
// employeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
const hireType = employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  components: {
    addorEdit,
    AssignRole
  },
  data() {
    return {
      curId: '',
      AssignRoleDialog: false,
      page: 1,
      pagesize: 10,
      list: [],
      total: 0,
      showDialog: false,
      showCodeDialog: false // 控制二维码弹层显示和隐藏
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    AssignRole(id) {
      this.curId = id
      this.AssignRoleDialog = true
    },
    showCode(url) {
      if (url) {
        this.showCodeDialog = true
        this.$nextTick(() => {
          const canvas = this.$refs.myCanvas
          QRCode.toCanvas(canvas, url)
        })
      } else {
        this.$message.error('请输入正确的图片')
      }
    },
    exportExcel() {
      // import('@/vendor/Export2Excel')  懒加载的方式导入一个模块， 返回值是一个promise实例
      import('@/vendor/Export2Excel').then(excel => {
        // excel指的模块对象，那么就可以使用这个模块对象去调用这个模块里面的函数或者访问变量   excel.函数名()
        const { tHeader, data } = this.transZhKeyToExcel(this.list)
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // console.log(list, 'listaaaaaaaaaaaaaaaaaaaa')
        // const data = this.formatJson(filterVal, list)
        // console.log(data, 'dataaaaaaaaaaaaaaaaa')
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },
    transZhKeyToExcel(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 1.判断数组有没有数据 没有数据直接终止执行
      const one = list[0]
      if (!one) return
      // 2.获得 中文 tHeader 表格头部
      // Object.keys(mapInfo) 取到英文名称
      // 通过map遍历数组 根据英文名称找到对应的中文名称 返回 新数组
      const tHeader = Object.keys(one).map(enkey => {
        return mapInfo[enkey]
      })
      // 2.获得 表格数据
      // 遍历数组 使用 Object.values(item) 获取数据
      const data = list.map(item => {
        return Object.values(item)
      })
      return { tHeader, data }
    },
    hSuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.pagesize)
      this.page = maxPage
      this.loadEmployees()
      this.showDialog = false
    },
    doDel(id) {
      this.$confirm('您确定要删除该部门吗', '是否继续', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        console.log(id)
        const res = await delEmployees(id)
        console.log(res)
        if (res.code === 10000) {
          this.$message.success(res.message)
          if (this.list.length === 1) {
            this.page--
            if (this.page <= 0) {
              this.page = 1
            }
          }
        }
        this.loadEmployees()
      })
    },
    formatData(id) {
      // console.log(employeesEnum.hireType)
      // 结果  [{ id: 1, value: '正式' },
      //        { id: 2, value: '非正式' }]
      // return employeesEnum.hireType.find(item => item.id === id).value
      return hireType[id] || '未知'
    },
    async loadEmployees() {
      const res = await getEmployees({ page: this.page, pagesize: this.pagesize })
      if (res.code === 10000) {
        this.$message.success(res.message)
        this.list = res.data.rows
        this.total = res.data.total
      }
    },
    handleCurrentChange(val) {
      this.page = val
      this.loadEmployees()
    }
  }
}
</script>
